package org.hit.burkun.stat;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.hit.burkun.db.DBHelper;

/**
 * Construct @ circle from the content
 * 
 * @author mingchen
 * @date 2015年8月10日
 */
public class AtCircle {

	private DBHelper dbh;

	public AtCircle() {
		init();
	}

	/**
	 * 
	 * Initialize the DB handler void 2015年8月10日
	 */
	public void init() {
		dbh = DBHelper.getServerDataDBHelper();
		dbh.connectionDB();
	}


	public void extractAtInfo() {
		String sql = "select uid,group_concat(content) from sina_train group by uid";
		Collection<String[]> res = dbh.queryData(sql, 2);
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		for (String[] s : res) {
			Pattern pattern = Pattern.compile("@([\\u4e00-\\u9fa5a-zA-Z\\d_-]{1,30})");
			Matcher matcher = pattern.matcher(s[1]);
			List<String> list = new ArrayList<String>();
			while (matcher.find()) {
				list.add(matcher.group(1));
			}
			map.put(s[0], list);
			System.out.println(StringUtils.join(list, "::"));
		}
		Serialization.save(map, "atinfo.out");
	}

	@SuppressWarnings("unchecked")
	public void atInfoStat(int limit) {
		Map<String, List<String>> map = (Map<String, List<String>>) Serialization.load("atinfo.out");
		Map<String, Integer> result = new HashMap<String, Integer>();
		BufferedWriter bw = null;
		try{
			bw = new BufferedWriter(new FileWriter("data/atstat.out"));
		}catch(IOException e){
			e.printStackTrace();
		}
		int i = 0, j = 0;
		HashSet<String> inter = new HashSet<String>();
		for (String outer : map.keySet()) {
			i += 1;
			j = 0;
			for (String inner : map.keySet()) {
				j += 1;
				if (map.get(outer).size()>0 && map.get(inner).size()>0 && outer.compareTo(inner) > 0) {
					inter.addAll(map.get(outer));
					inter.retainAll(map.get(inner));
					if (inter.size() >= limit) {
						try {
							bw.write(outer+"\t"+inner+"\t"+String.valueOf(inter.size())+"\n");
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				System.out.println(i + " | " + j + " | " + map.size());
			}
		}
		try {
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
